/**
 *
 */
package jp.seraph.same.controller;

import java.io.IOException;

import jp.seraph.same.message.MessageUtil;
import jp.seraph.same.model.DefaultMotionModel;
import jp.seraph.same.model.MotionManagerModel;
import jp.seraph.same.model.MotionModel;

import org.apache.commons.lang.NullArgumentException;

/**
 *
 */
public class DefaultMotionManagerController implements MotionManagerController {
    public DefaultMotionManagerController(MotionManagerModel aMotionManager){
        if(aMotionManager == null)
            throw new NullArgumentException("aMotionManager");

        mMotionManger = aMotionManager;
    }

    private MotionManagerModel mMotionManger;

    /**
     * @see jp.seraph.same.controller.MotionManagerController#createMotion(java.lang.String)
     */
    public MotionModel createMotion(String aMotionName) {
        MotionModel tNewModel = new DefaultMotionModel(aMotionName);
        this.addMotion(aMotionName, tNewModel);

        return tNewModel;
    }

    private void addMotion(String aName, MotionModel aModel){
        mMotionManger.add(aModel);
    }

    /**
     * @see jp.seraph.same.controller.MotionManagerController#getMotion(java.lang.String)
     */
    public MotionModel getMotion(String aMotionName) {
        return mMotionManger.get(aMotionName);
    }

    /**
     * @see jp.seraph.same.controller.MotionManagerController#removeMotion(java.lang.String)
     */
    public MotionModel removeMotion(String aMotionName) {
        return mMotionManger.remove(aMotionName);
    }

    /**
     * @see jp.seraph.same.controller.MotionManagerController#removeMotion(jp.seraph.same.model.MotionModel)
     */
    public MotionModel removeMotion(MotionModel aTarget) {
        return mMotionManger.remove(aTarget);
    }

    /**
     * @see jp.seraph.same.controller.MotionManagerController#commit()
     */
    public void commit() throws IOException {
        mMotionManger.save();
    }

    public void open() throws IOException {
        mMotionManger.open();
    }

    public void renameMotion(String aOldName, String aNewName) {
        String tOldName = aOldName;
        String tNewName = aNewName;
        if(tOldName.equals(aNewName))
            return;

        if("".equals(tNewName))
            throw new IllegalArgumentException(MessageUtil.cannotUseEmptyString());

        if(mMotionManger.get(tNewName) != null)
            throw new IllegalArgumentException(MessageUtil.duplicateMotionName(tNewName));

        MotionModel tTargetModel = mMotionManger.get(tOldName);
        if(tTargetModel == null)
            throw new IllegalArgumentException(MessageUtil.motionNotFound(tOldName));

        mMotionManger.remove(tOldName);
        tTargetModel.setName(tNewName);
        mMotionManger.add(tTargetModel);
    }
}
